// pages/installation-maintenance/installation-maintenance.js
import WxValidate from '../../utils/wxValidate'

// 验证字段的规则
const rules = {
  // merchant_id: {
  //   required: true
  // },
  address: {
    required: true,
  },
  contcat_phone: {
    required: true,
    tel: true,
  },
  contcat_name: {
    required: true,
  },
  memo: {
    required: true,
  }
}

// 验证字段的提示信息，若不传则调用默认的信息
const messages = {
  // merchant_id: {
  //   required: '请选择门店'
  // },
  address: {
    required: '请填写地址',
  },
  contcat_phone: {
    required: '请填写联系电话',
    tel: '联系电话格式不正确',
  },
  contcat_name: {
    required: '请填写联系人',
  },
  memo: {
    required: '请填写问题',
  }
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    applyData: {
      address: '',
      contcat_name: '',
      contcat_phone: '',
      apply_time: '',
      memo: '',
      merchant_id: '',
      annex: []
    },
    merchant_name: '',
    errorMessage: {},
    autosize: {
      minHeight: 80
    },
    merchantList: [],
    fileList: [], // 附件预览
    show: false,
  },
  // 显示弹窗
  showHandle() {
    this.setData({
      show: true
    })
  },
  // 关闭 弹窗
  closeHandle() {
    this.setData({
      show: false
    })
  },
  selectHandle(event) {
    const merchant = event.detail
    this.setData({
      merchant_name: merchant.merchant_name,
      'applyData.merchant_id': merchant.id
    })
  },
  // 删除附件
  deleteHandle(event) {
    const {index} = event.detail;

    const { fileList,  applyData} = this.data;
    fileList.splice(index, 1)
    applyData.annex.splice(index, 1)
    this.setData({
      fileList
    })
  },
  afterReadHandle(event) {
    const file = event.detail.file;

    const { fileList, applyData } = this.data;

    wx.showLoading({
      title: '上传中...',
    })
    wx.ajax.uploadFile({
      filePath: file.url,
      callback: (url) => {
        wx.hideLoading()
        if (url) {
          fileList.push(file);
          applyData.annex.push(url);
          this.setData({
            fileList,
            'applyData.annex': applyData.annex
          });
        }
      },
    });
  },

  fieldChangeHandle(event) {
    const {name} = event.currentTarget.dataset
    const value = event.detail
    this.setData({
      [`applyData.${name}`]: value
    })
  },

  blurHandle(event) {
    const {name} = event.currentTarget.dataset
    const value = this.data.applyData[name]
    this.setData({
      [`errorMessage.${name}`]: this.wxValidate.validateField(name, value)
    })
  },

  // 提交数据
  submitHandle() {
    // 传入表单数据，调用验证方法
    if (!this.wxValidate.checkForm(this.data.applyData)) {
      let errorMessage = {}
      this.wxValidate.errorList.forEach(item => {
        errorMessage[item.param] = item.msg
      })
      this.setData({errorMessage})
    } else {
      this.requestSave(this.data.applyData)
    }
  },

  // 请求关注的门店信息
  requestMerchantList() {
    wx.ajax.post('findUserAllMerchant.action').then(res => {
      let merchantList = res.result || [];
      let merchant;

      if (this.merchant_id) {
        merchant = merchantList.find(item => item.id == this.merchant_id)
      }

      merchantList.forEach(item => {
        item.name = item.merchant_name
      })

      this.setData({
        merchantList,
        merchant_name: merchant ? merchant.merchant_name : '',
        'applyData.merchant_id': merchant ? merchant.id : ''
      })
    })
  },
  // 请求保存
  requestSave(data) {
    data = {...data}
    data.annex = data.annex.join(',')
    wx.ajax.post('wxazApply.action', data, true).then(res => {
      wx.showToast({
        title: '提交成功！',
        icon: 'success',
        duration: 2000,
        mask: true,
        success() {
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1800)
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {merchant_id} = options

    this.merchant_id = merchant_id

    this.requestMerchantList()

    this.wxValidate = new WxValidate(rules, messages)

    wx.hideShareMenu();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: `/pages/installation-maintenance/installation-maintenance?merchant_id=${this.data.applyData.merchant_id}`
    }
  }
})